<?php
/*
 * code to update user details either posted from admin edituser.php form
 * or user editing own details from editmyuser.php
*/

include("../inc_files/utils/checksession.php");
// Create connection
include("../inc_files/utils/dbconnection.php");

// add the function to create a salt for encryption
include("../inc_files/utils/salt.php");

//sanitise the input data

$firstName = $mysqli->real_escape_string($_POST['firstname']);
$lastName = $mysqli->real_escape_string($_POST['lastname']);
$password = $_POST['password'];
$userRole = $mysqli->real_escape_string($_POST['userrole']);

if(isset($_POST['disabled'])){
	$disabled = $mysqli->real_escape_string($_POST['disabled']);
	if(trim($_POST['disabled'])==true){
		$disabled = 1;
	}

} else {
	$disabled = 0;
}


//if the form post came from the user's update details form
if($userRole == "_self")
{
	$userID = $_SESSION["userid"];
	if(strlen($password) < 7){
		$query="UPDATE staff SET FirstName = ?, LastName = ? WHERE UserID = ?;";
		if($stmt = $mysqli -> prepare($query))	{
			$stmt -> bind_param("sss", $firstName, $lastName,  $userID);
		}
	} else {
		$hashPassword = crypt(trim($_POST['password']),createSalt());
		$query="UPDATE staff SET FirstName = ?, LastName = ?, Password = ? WHERE UserID = ?;";
		if($stmt = $mysqli -> prepare($query))	{
			$stmt -> bind_param("ssss", $firstName, $lastName,  $hashPassword, $userID);
		}
	}
	//otherwise it came from the admin form
} else {
	$userID = $mysqli->real_escape_string($_POST['userid']);
	if(strlen($password) < 7){
		$query="UPDATE staff SET FirstName = ?, LastName = ?, Role = ?, Disabled = ? WHERE UserID = ?;";
		if($stmt = $mysqli -> prepare($query))	{
			$stmt -> bind_param("sssss", $firstName, $lastName, $userRole, $disabled, $userID);
		}
	} else {
		$hashPassword = crypt(trim($_POST['password']),createSalt());
		$query="UPDATE staff SET FirstName = ?, LastName = ?, Role = ?, Disabled = ?, Password = ? WHERE UserID = ?;";
		if($stmt = $mysqli -> prepare($query))	{
			$stmt -> bind_param("ssssss", $firstName, $lastName, $userRole, $disabled, $hashPassword, $userID);
		}
	}
}


//execute the query
$stmt -> execute();

//tidy up database connection
$mysqli->close();

if($userRole == "_self")
{
	$_SESSION['firstName'] = $firstName;
	$_SESSION['lastName'] = $lastName;
	header("Location:../home/home.php");
} else {

	header("Location:listusers.php");
}

?>


